//在使用的View中引入WxParse模块
var WxParse = require('../wxParse/wxParse.js');
var util = require('../../utils/util.js')
var app = getApp()
let willPay = false
Page({
  data: {
    goodsid: '',	// 商品id，一件商品的话就是goodsid，但是包含上衣上衣，裤子的套装是另一个套装id
    suit: 0,			// 是否是套装
    product: '',	// 商品数据
    goodsImage: '',	// 商品图片
    animationData: '',
    maskVisual: 'hidden',
    goodsids: '',		// 商品id数组，套装包含上衣裤子id
    goodsSizes: '',
    ratio: "ration_0",
    cloth: '',		// 是否是上衣尺码尺码
    sizeData: '',	// 尺码信息
    clothEurCode: '',	// 上衣码
    clothShape: '',		// 上衣体型
    pantsEurcode: '',	// 下衣码
    pantsShape: '',		// 下衣体型
    productCount: '1',
    payParam: {},
    ontType: '尺码',
    condition: true,//选择量体数据的条件
    checked: false,
    //下面弹窗是否显示
    loadsize: true,
    isfrom: 2,
    measureId: "",
    mohuanUser: "",
    measureshow: false,
    returnCode: "",
    tomeasure: false,
    tomeasuredata: true,
    xiongwei:"0",
    jiankuan:"0",
    yaowei:"0",
    xiuchang:"0",

    xiayiyaowei: "0",
    tunwei:"0",
    kuchang:"0",
    kukou:"0",

    shangyi:"",
    xiayi:"",
    condition:true,
    categoryId:"",
    mygoodsid: null,//如果是套装则是上衣id
    // havecixiu:1,
    // cixiuData:null

  },
  switch2Change: function (e) {
    console.log('switch2 发生 change 事件，携带值为', e.detail.value)

    if (e.detail.value == true) {
      this.setData({
        loadsize: false,
        // checked:true
      })
    } else {
      this.setData({
        loadsize: true,
        // checked:false
      })
    }
  },
  onShow: function () {

    var that = this;
    //获取用户量体数据
    // debugger
    var url = 'https://www.magicmanufactory.com/c2mwebservice/api/v2/public/measure/distribution/' + this.data.mohuanUser.memberInfo.phoneNo
    console.log(url)
    wx.request({
      url: url,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        that.setData({
          returnCode: res.data.returnCode
        })
        //返回200代表有量体数据。400表示没有量体数据
        console.log("-----------------------returnCode-->" + that.data.returnCode)
        if (that.data.returnCode == 400 || that.data.returnCode == null) {
          that.setData({
            tomeasure: true,
            tomeasuredata: false
          })
        } else {
          that.setData({
            tomeasure: false,
            tomeasuredata: true
          })
        }
      }
    })


  },
  //页面一加载获取尺码信息
  onLoad: function (params) {
    console.log("接收到来自上个页面的数据" + JSON.stringify(params));
    this.setData({
      mohuanUser: app.globalData.mohuanUser
    })

    let that = this;
    let myurl = `/c2mwebservice/api/v2/public/goods/microCustom/goodsInfo/${params.goodsid}/${params.suit}`;
    console.log("***********此商品的url****" + myurl);
    util.request(`/c2mwebservice/api/v2/public/goods/microCustom/goodsInfo/${params.goodsid}/${params.suit}`, function (res) {
      let oneType = "尺码"
      //如果length>1，则是套装
      if (res.returnData.goodsList.length > 1) {
        oneType = "上衣尺码"
      }
      that.setData({
        product: res.returnData,
        goodsImage: res.returnData.pictureUrl,
        oneType: oneType,
        categoryId: res.returnData.goodsList[0].categoryId,
        mygoodsid: res.returnData.goodsList[0].goodsUid//如果是套装则取上衣ID
      });
     
      that._loadProductInfoDetail(res.returnData)
      //that.judgeBrede()
    }, function (error) {

    });
    this.setData({
      goodsid: params.goodsid,
      suit: params.suit,
    })
    try {
      var value = wx.getStorageSync('measureId')
      if (value) {
        // Do something with return value
        console.log("接收到来自量体页面的measureID------------------------------>>>>" + value)
        this.setData({
          measureId: value
        })
      }
    } catch (e) {
      // Do something when catch error
    }
  
  },
  onShareAppMessage: function () {//只有定义了此事件处理函数，右上角菜单才会显示 “转发” 按钮
    return {
      title: '商品分享',
      desc: '酷特云蓝'
    }
  },
  //判断商品有无刺绣信息
  // judgeBrede:function(){
  //   //接收this，防止闭包
  //   let that=this;
  //   let params={
  //     "categoryId": this.data.categoryId,
  //     "goodsId": this.data.mygoodsid
  //   }
  //   console.log("传入刺绣接口的params为"+JSON.stringify(params))
  //   wx.request({
  //     url: 'https://www.magicmanufactory.com/c2mwebservice/api/v2/public/embroids/microCustom',
  //     data: params,
  //     header: {
  //       'content-type': 'application/json' ,
  //       'C2M-Identify':'Platform:Android,APP Version:6.0,OS Version:9.3,Device Type:iphonevice Type:Android'
     
  //     },
  //     method:'post',
  //     success: function (res) {
  //       console.log(res.data)
  //       if (JSON.stringify(res.data.returnData) == "{}"){
  //         //this获取不到，闭包
  //         that.setData({
  //           havecixiu: 0
  //         })
  //       }else{
  //         that.setData({
  //           cixiuData:res.data.returnData
  //         })
  //       }
        
        
  //     }
  //   })
  // },
  //加载产品详细信息
  _loadProductInfoDetail: function (returnData) {
    let that = this
    console.log("categoryId" + this.data.categoryId)
    let id=this.data.categoryId
    if(id==36||id==34||id==35||id==45){
    that.setData({
      condition:false
    })
    }
 
    wx.request({
      url: returnData.introUrl,
      success: function (res) {
        var mhtml = res.data;
        var nhtml = mhtml.replace(/<!doctype html>\n/, '').replace("<!doctype html>", "").replace("详情页", "").replace("Detail display", "").replace("细节展示", "").replace("Size table", "").replace("尺码表", "");
        var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
        while (SCRIPT_REGEX.test(nhtml)) {//传入文档对象，获取整体内容
          nhtml = nhtml.replace(SCRIPT_REGEX, ""); //正则替换为空
        }
        var reg = /<div class=\"rexiao\">.*?<a.*?>(.*?)<\/a>.*?<\/div>/g;
        nhtml = nhtml.replace(reg, ""); //正则替换为空
        WxParse.wxParse('article', 'html', nhtml, that, 5);
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete

      }
    })
  },

  //处理购买产品
  handleBuyProduct: function (event) {
    let that = this;
  },

  //显示选择尺寸视图
  showSelectSizeView: function (event) {
 

    let sizes = new Array();
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    })
    let that = this;
    let clothid = this.data.product.goodsList[0].goodsUid;
    console.log("上衣尺码的clothid为"+clothid);
    // 查询尺码
    util.request(`/c2mwebservice/api/v1/public/sizes/goods/${clothid} `, function (dataJson) {
      sizes[0] = dataJson.returnData.valueList;	//上衣数据
      console.log("*********上衣数据为*********"+JSON.stringify(dataJson))
      that.setData({
        shangyi: dataJson.returnData.valueList
      })
      //如果是均码，上面的swipe不显示
      if (dataJson.returnData.valueList[0].data[0].eurCode == "均码") {
        that.setData({
          condition: false,
        })

      }
      if (that.data.product.goodsList.length > 1) {
        let pantid = that.data.product.goodsList[1].goodsUid;
        console.log("下衣尺码的pantid为" + pantid);
        util.request(`/c2mwebservice/api/v1/public/sizes/goods/${pantid} `, function (dataJson) {
          wx.hideToast()
          console.log("*********下衣数据为*********" + JSON.stringify(dataJson))
          sizes[1] = dataJson.returnData.valueList;	//裤子数据
          that.setData({
            goodsSizes: sizes,
            ratio: "ratio_1",
            xiayi:dataJson.returnData.valueList
          })
        }, function (reason) {
          wx.hideToast()
        })
      }
      else {
        wx.hideToast();
        that.setData({
          goodsSizes: sizes,
          ratio: "ratio_0"
        })
      };
    }, function (reason) {
      wx.hideToast()
      wx.showToast({
        title: '加载失败，请稍后再试',
      })
    });

    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease-in-out', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
    })

    this.animation = animation;
    animation.translateY(-400).step();
    this.setData({
      animationData: this.animation.export(),
      maskVisual: 'show',
    });
  },
  //选择尺码
  bindViewTap: function (event) {
    var that=this;
    console.log(event);
    console.log(event.currentTarget.dataset.eurcode);
    console.log(event.currentTarget.dataset.shape);
    // let code = event.currentTarget.dataset.eurcode;
    // let shape = event.currentTarget.dataset.shape;
    // let cloth= event.currentTarget.dataset.cloth;
    this.setData({
      // checked: false,
      loadsize: true
    });
    let cloth = event.target.dataset.cloth
    let sizeData = event.target.dataset.sizedata
    let code = event.target.dataset.eurcode
    let shape = event.target.dataset.shape
    let clothCode = this.data.clothEurCode
    let clothShape = this.data.clothShape
    let pantsCode = this.data.pantsEurcode
    let pantsShape = this.data.pantsShape
    //如果是上衣
    if (cloth == '1') {
      clothCode = code
      clothShape = shape
      for(var i=0;i<this.data.shangyi.length;i++){
        if (clothShape==this.data.shangyi[i].bodyShape){
          for (var j = 0; j < this.data.shangyi[i].data.length;j++){
            if (clothCode==this.data.shangyi[i].data[j].eurCode){
                that.setData({
                  xiongwei: this.data.shangyi[i].data[j].chestCircle,
                  jiankuan: this.data.shangyi[i].data[j].jianWidth,
                  yaowei: this.data.shangyi[i].data[j].miWaistCircle,
                  xiuchang: this.data.shangyi[i].data[j].xiuChang
                })
            }
          }         
        }
      }
    }
    //下衣 
    else {
      pantsCode = code
      pantsShape = shape
      for (var i = 0; i < this.data.xiayi.length; i++) {
        if (pantsShape == this.data.xiayi[i].bodyShape) {
          for (var j = 0; j < this.data.xiayi[i].data.length; j++) {
            if (pantsCode == this.data.xiayi[i].data[j].eurCode) {
              that.setData({
                xiayiyaowei: this.data.xiayi[i].data[j].waistCircle,
                tunwei: this.data.xiayi[i].data[j].hipCircle,
                kuchang: this.data.xiayi[i].data[j].pantsLen,
                kukou: this.data.xiayi[i].data[j].kuKou
              })
            }
          }
        }
      }
    };
    this.setData({
      cloth: cloth,
      sizeData: sizeData,
      clothEurCode: clothCode,
      clothShape: clothShape,

      pantsEurcode: pantsCode,
      pantsShape: pantsShape
    });
  },


  //减少数量
  minusQuantity: function (event) {
    let count = this.data.productCount
    if (count <= 1) {
      return;
    }
    count--;
    this.setData({
      productCount: count
    })
  },

  //增加数量
  addQuantity: function (event) {
    let count = this.data.productCount
    if (count >= 5) {
      return;
    }
    count++;
    this.setData({
      productCount: count
    })
  },

  //关闭 选择尺码view
  dismissSelectSizeView: function () {
    this.animation.translateY(400).step();
    this.setData({
      animationData: this.animation.export(),
      maskVisual: 'hidden'
    });
  },
  //组装上衣bean
  _configureClothParam: function (cloth) {
    let checked = this.data.checked;
    let goodstype = 3
    if (cloth.color) {
      goodstype = 4
    }
    let clothParam = {}
    clothParam.brandId = cloth.brand.brandId;
    clothParam.brandName = cloth.brand.brandName;
    clothParam.complete = 1;
    clothParam.count = this.data.productCount;
    clothParam.customization = {}
    clothParam.customization.categoryId = cloth.categoryId;
    clothParam.customization.categoryName = cloth.categoryName;
    clothParam.customization.design = cloth.design;
    clothParam.customization.kind = cloth.kind;
    clothParam.customization.material = cloth.materials[0];
    clothParam.customization.positions = cloth.customPositions;
    clothParam.free = 0;
    clothParam.giftCardUsePercent = 1;
    clothParam.goodsId = cloth.goodsUid;
    clothParam.goodsName = cloth.goodsName;
    clothParam.goodsType = goodstype;
    clothParam.isValid = 1;
    clothParam.personalise = { embroidery: [] }
    clothParam.purchaseQuantityLimit = cloth.purchaseQuantityLimit;
    clothParam.salesPromotionId = cloth.salesPromotionId;
    clothParam.price = cloth.goodsSellPrice;
    if (this.data.loadsize == true) {
      clothParam.size = {
        bodyShape: this.data.clothShape,
        size: this.data.clothEurCode,
        sizeType: 1
      }
    } else {
      clothParam.size = {
        bodyShape: "",
        size: "",
        sizeType: 2,
        measureId: this.data.measureId
      }
    }
    return clothParam
  },
  //组装下衣bean
  _configureClothParam2: function (cloth) {
    let checked = this.data.checked;
    let goodstype = 3
    if (cloth.color) {
      goodstype = 4
    }
    let clothParam = {}
    clothParam.brandId = cloth.brand.brandId;
    clothParam.brandName = cloth.brand.brandName;
    clothParam.complete = 1;
    clothParam.count = this.data.productCount;
    clothParam.customization = {}
    clothParam.customization.categoryId = cloth.categoryId;
    clothParam.customization.categoryName = cloth.categoryName;
    clothParam.customization.design = cloth.design;
    clothParam.customization.kind = cloth.kind;
    clothParam.customization.material = cloth.materials[0];
    clothParam.customization.positions = cloth.customPositions;
    clothParam.free = 0;
    clothParam.giftCardUsePercent = 1;
    clothParam.goodsId = cloth.goodsUid;
    clothParam.goodsName = cloth.goodsName;
    clothParam.goodsType = goodstype;
    clothParam.isValid = 1;
    clothParam.personalise = { embroidery: [] }
    clothParam.purchaseQuantityLimit = cloth.purchaseQuantityLimit;
    clothParam.salesPromotionId = cloth.salesPromotionId;
    clothParam.price = cloth.goodsSellPrice;
    if (this.data.loadsize == true) {
      clothParam.size = {
        bodyShape: this.data.pantsShape,
        size: this.data.pantsEurcode,
        sizeType: 1
      }
    } else {
      clothParam.size = {
        bodyShape: "",
        size: "",
        sizeType: 2,
        measureId: this.data.measureId
      }
    }
    return clothParam
  },
  //处理支付
  handlePayAction: function () {
    // debugger
    //组装params
    let measureId = this.data.measureId;
    let loadsize = this.data.loadsize;
    if (loadsize == false && measureId == null) {
      wx.showToast({
        title: '请选择量体数据或者选择尺码',
      })
      return;
    }
    let params = {}
    let cloth = this.data.product.goodsList[0];
    // console.log(cloth);
    let clothParams = this._configureClothParam(cloth);
    params.goods = [clothParams];
    params.isValid = 0;
    if (this.data.product.goodsList.length > 1) {
      // let pantsParams = this._configureClothParam(this.data.product.goodsList[1]);
      let pants = this.data.product.goodsList[1];
      // console.log(pants);
      let pantsParams = this._configureClothParam2(pants);

      params.goods = [clothParams, pantsParams];
      params.suit = {
        suitCount: this.data.productCount,
        suitId: this.data.product.goodsId,
        suitNameCn: this.data.product.goodsNameCn,
        suitNameEn: this.data.product.goodsNameEn,
        suitPrcUrl: '',
        suitPrice: this.data.product.salePrice
      }
    }
    // 存储商品bean
    wx.setStorage({
      key: 'productInfo',
      data: params,
      success: function (res) {
        console.log('数据存储成功')
        // console.log(params)
      },
      fail: function () {
        console.log('数据存储失败')
      },
      complete: function () {
      }
    })

    this._goPay(params)
  },

  //去结算按钮 单击
  _goPay: function (params) {
    // debugger
    let _this = this
    let measureId = _this.data.measureId;
    //先判断登录,登录过后的代码
    if (!this._judgeLogin()) {
      if (_this.data.loadsize == true) {
        //判断是否是套装，选择尺码
        if (_this.data.suit == "1") {

          if (_this.data.clothEurCode.length == 0 ||
            _this.data.pantsEurcode.length == 0) {
            wx.showToast({
              title: '有未选择的尺码，请选择',
            })
            return;
          }
        } else {
          if (_this.data.clothEurCode.length == 0) {


            wx.showToast({
              title: '有未选择的尺码，请选择',
            })
            return;
          }
        };
      }
      let mohuanUser = app.globalData.mohuanUser
      let memberId = mohuanUser.memberId
      // console.log("params为" + params);
      console.log("传入的json为" + JSON.stringify(params));
      console.log("会员ID为" + memberId);

      //验证通过，则跳转支付页面
      util.postRequest(`/c2mwebservice/api/v2/${memberId}/shoppingCart/order`, params, function (res) {
        wx.navigateTo({
          url: `../orderSure/orderSure?productImage=${_this.data.goodsImage}&orderId=${res.returnData}`,

        })
      }, function (res) {
        console.log("-------------->" + res)
        wx.showToast({
          title: res.data.returnMsg,
          duration: 2000
        })
      });
    }
  },

  //判断是否登录
  _judgeLogin: function () {
    let mohuanUser = app.globalData.mohuanUser
    if (mohuanUser == null) {
      wx.navigateTo({
        url: '../login/login',
        success: function (res) {
          willPay = true
        }
      })
      return true
    }
    return false
  },
  //悬浮框 手指触摸动作开始
  moveMeasureStart: function (e) {
    this.setData({
      scrollY: false
    })
  },
  //悬浮框 手指触摸后移动
  moveMeasure: function (e) {
    this.setData({
      movePosition: `left: ${e.changedTouches[0].pageX - 36}px; top: ${e.changedTouches[0].pageY - 36}px`
    })
  },
  //悬浮框 手指触摸动作结束
  moveMeasureEnd: function (e) {
    let left = (e.currentTarget.offsetLeft > app.globalData.deviceInfo.windowWidth / 2.0 - 36) ? app.globalData.deviceInfo.windowWidth - 16 - 72 : 16
    let top = e.changedTouches[0].pageY - 36
    if (top < 0) {
      top = 0
    } else if (top > app.globalData.deviceInfo.windowHeight - 72) {
      top = app.globalData.deviceInfo.windowHeight - 72
    }
    this.setData({
      movePosition: `left: ${left}px; top: ${top}px`,
      scrollY: true
    })
  },
  //悬浮框 单击时
  tapMeasure: function (e) {
    var temp = getApp().globalData.mohuanUser;
    if (temp == "" && temp == null && temp == undefined) {
      wx.showToast({
        title: '未登录',
      })
    }

    let that = this
    //预约量体登录验证  未登录跳转登录页
    if (!getApp().globalData.mohuanUser || !getApp().globalData.mohuanUser.memberId || getApp().globalData.mohuanUser.memberId.length == 0) {
      wx.navigateTo({ url: '../login/login' })
      return
    }

    // wx.showToast({ title: temps, icon: 'loading', uration: 20000 })
    util.request(`/c2mwebservice/api/v2/members/${getApp().globalData.mohuanUser.memberId}/measureOrder/list?orderStatus=10004_10002_10003_10007_10008`, function (res) {
      //wx.hideToast()
      let dataArr = res.returnData
      if (dataArr.length == 0) {
        wx.switchTab({
          url: '../newMeasure/newMeasure'
        })

      } else {
        let status = parseInt(dataArr[0].orderStatus)
        switch (status) {
          case 10003: { wx.switchTab({ url: '../newMeasure/newMeasure' }) }
          case 10002: {
            that.showHaveMeasureOrder('已成功预约', '请等待量体师与您联系', dataArr[0].orderId)
          }
            break
          case 10004:
          case 10007: {
            that.showHaveMeasureOrder('', `量体师--${dataArr[0].tailor.personName}即将为您服务!\n联系电话${dataArr[0].tailor.phoneNo}`, dataArr[0].orderId)
          }
            break
          case 10008: {
            that.showHaveMeasureOrder('', `量体师--${dataArr[0].tailor.personName}即将为您服务!\n联系电话${dataArr[0].tailor.phoneNo};\n预约量体时间${dataArr[0].appointTime}`)
          }
          default: {
            wx.switchTab({ url: '../newMeasure/newMeasure' })
          }
            break
        }
      }
    }, function () {

    })
  },
  //跳转到量体数据页面
  Presstext: function (e) {
    wx.navigateTo({
      url: `../measureData/measureList?isfrom=2`,
      success: function (res) {
      },
      fail: function () {
      },
      complete: function () {
      }
    })
  },
  tomeasurePage: function () {
    wx,wx.navigateTo({
      url: '../newMeasure/newMeasure', 
    })
  },

  //取消量体预约
  showHaveMeasureOrder(title, message, orderId) {
    let showCancel = orderId ? true : false
    wx.showModal({
      title: title,
      content: message,
      cancelText: '取消预约',
      showCancel: showCancel,
      success: function (res) {
        if (!res.confirm) {
          wx.showToast({ title: 'loading..', icon: 'loading', uration: 20000 })
          util.postRequest(`/c2mwebservice/api/v1/members/${getApp().globalData.mohuanUser.memberId}/cancellation/measurements`,
            { "orderId": orderId, "cancelReasons": { "reasonId": 4, "reasonContent": "其他", "extraContent": "" } }, function (res) {
              wx.hideToast()
            }, function (res) {
              wx.hideToast()
            })
        }
      }
    })
  },
//刺绣按钮点击事件
  // showBredeView(){
  //   let that=this;
  //   //将对象转换成字符串传递
  //   var cixiuData=JSON.stringify(that.data.cixiuData)
  //   wx.navigateTo({
  //     url: `../brede/brede?cixiuData=${cixiuData}`

  //   })
  // }
})